<template>
  <Card dis-hover :bordered="false">
    <Form
      ref="create"
      :model="contentInfo"
      :rules="rules"
      :label-width="120"
      style="width: 800px"
    >
      <FormItem label="标题" prop="title" required>
        <Input
          v-model="contentInfo.title"
          placeholder="请输入标题（50字以内）"
          :maxlength="30"
        />
      </FormItem>

      <FormItem label="形象图" prop="type" required>
        <RadioGroup v-model="contentInfo.type" @on-change="changeType">
          <Radio :label="1"><span>图片</span></Radio>
          <Radio :label="2"><span>视频</span></Radio>
        </RadioGroup>
      </FormItem>

      <FormItem
        label="视频"
        prop="videofiles"
        v-if="contentInfo.type == 2"
        required
      >
        <Upload
          :action="fileUrl"
          :accept="supportVideo"
          :show-upload-list="false"
          :before-upload="videoBeforeUpload"
          :on-error="videoUploadError"
        >
          <Button type="primary" :loading="loadingUpload">上传</Button>
          <Tooltip
            :max-width="300"
            placement="top"
            :content="'支持视频格式：' + supportVideo"
            class="ivu-ml-8"
          >
            <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
          </Tooltip>
        </Upload>
        <Progress
          v-if="progress && progress != 100"
          :percent="progress"
          :stroke-width="5"
        />
        <ul class="ivu-upload-list" v-if="contentInfo.videofiles.file">
          <li
            class="ivu-upload-list-file ivu-upload-list-file-finish"
            style="display: inline-block"
          >
            <span
              @click="
                handleView(
                  contentInfo.videofiles.file_url || contentInfo.videofiles.url,
                  'video'
                )
              "
              ><Icon type="ios-videocam" />
              {{ contentInfo.videofiles.file }}</span
            >
            <i
              class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
              @click="removeVideo"
            ></i>
          </li>
        </ul>
      </FormItem>
      <FormItem
        label="封面图"
        prop="imgfiles"
        v-if="contentInfo.type == 1"
        required
      >
        <Upload
          :action="fileUrl"
          :accept="supportImg"
          multiple
          :show-upload-list="false"
          :before-upload="imgBeforeUpload"
          :on-error="imgUploadError"
        >
          <Button
            type="primary"
            :loading="loadingUpload"
            @click="showMaxSize = true"
            >上传</Button
          >
          <Tooltip
            :max-width="300"
            placement="top"
            :content="'支持图片格式：' + supportImg"
            class="ivu-ml-8"
          >
            <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
          </Tooltip>
        </Upload>
        <div class="imgList ivu-mt-16">
          <div
            class="demo-upload-list"
            v-for="item in contentInfo.imgfiles"
            :key="item.file_url"
          >
            <img :src="item.file_url" fit="cover" width="100" height="60" />
            <div class="demo-upload-list-cover">
              <Icon
                type="ios-eye-outline"
                size="30"
                @click="handleView(item.file_url)"
              ></Icon>
              <Icon
                type="ios-trash-outline"
                size="30"
                @click="handleRemove(item)"
              ></Icon>
            </div>
          </div>
        </div>
      </FormItem>
      <FormItem label="内容" prop="content" required>
        <Input
          v-model="contentInfo.content"
          type="textarea"
          :rows="10"
          placeholder="请输入内容"
        />
      </FormItem>
      <FormItem>
        <Button
          type="primary"
          @click="ok"
          :loading="btnLoading"
          v-hasC="{
            name: 'v1-system-config-edit-wx-mini',
            flag: 'v1/system-config/edit-wx-mini',
          }"
          >保存</Button
        >
      </FormItem>
    </Form>
    <Modal
      :mask-closable="true"
      v-model="visible"
      @on-visible-change="
        (e) => {
          onPause();
        }
      "
      :width="600"
      title="预览"
      :footer-hide="true"
      :draggable="true"
    >
      <video
        ref="video"
        :src="imgName"
        controls
        style="width: 100%"
        v-if="bigType == 'video'"
      ></video>
      <img :src="imgName" alt="" style="width: 100%" v-else />
    </Modal>
  </Card>
</template>
<script>
import { homeInfo, homeEdit, uploadFile } from "@api/home.js";
export default {
  data() {
    return {
      btnLoading: false,
      loadingUpload: false,
      controller: null,
      progress: 0,
      filesNum: [],
      maxFiles: 4,
      showMaxSize: false,
      fileUrl: "",
      supportVideo: "",
      supportImg: "",
      imgName: "",
      visible: false,
      bigType: "",
      contentInfo: {
        type: 1,
        title: "",
        content: "",
        videofiles: [],
        imgfiles: [],
      },
      rules: {
        type: [{ required: true, message: "请选择类型" }],
        content: [{ required: true, message: "请输入内容" }],
        title: [
          {
            required: true,
            pattern: /^.{1,50}$/,
            message: "请输入标题（50字以内）",
          },
        ],
        videofiles: [{ required: true, message: "请上传视频" }],
        imgfiles: [{ required: true, message: "请上传图片" }],
      },
    };
  },
  mounted() {
    homeInfo().then((res) => {
      this.contentInfo = {
        type: res.c_home_page_banner_type,
        title: res.c_home_page_title,
        content: res.c_home_page_banner_content,
        videofiles: res.c_home_page_banner_video,
        imgfiles: res.c_home_page_banner_image,
      };
      this.supportImg = res.image_type;
      this.supportVideo = res.video_type;
    });
  },
  methods: {
    changeType() {
      this.loadingUpload = false;
      if (this.controller) {
        this.progress = 0;
        this.controller.abort();
      }
    },
    videoBeforeUpload(e) {
      if (e.size > 20 * 1024 * 1024) {
        this.$Message.error("文件大小不能超过20M");
        return false;
      }
      this.loadingUpload = true;
      this.controller = new AbortController();
      this.progress = 0;
      uploadFile({ site: "wx_mini", module: "index_video", file: e }, this)
        .then((res) => {
          this.contentInfo.videofiles = res;
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    videoUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    imgBeforeUpload(e) {
      if (this.filesNum.length >= this.maxFiles) {
        if (this.showMaxSize) {
          this.$Message.success("图片数量不能超过" + this.maxFiles + "张！");
          this.showMaxSize = false;
        }
        return false;
      }
      if (e.size > 1024 * 1024 * 1) {
        this.$Message.error("文件大小不能超过1M");
        return false;
      }
      this.loadingUpload = true;
      this.filesNum.push(e);
      this.controller = new AbortController();
      uploadFile({ site: "wx_mini", module: "index_img", file: e }, this)
        .then((res) => {
          res.file_url = res.url;
          this.contentInfo.imgfiles.push(res);
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    imgUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    removeVideo() {
      this.contentInfo.videofiles = [];
    },
    handleView(name, type) {
      this.imgName = name;
      this.bigType = type;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.contentInfo.imgfiles;
      this.contentInfo.imgfiles.splice(fileList.indexOf(file.file), 1);
      this.filesNum.splice(fileList.indexOf(file.file), 1);
    },
    addForm() {
      if (this.loadingUpload) {
        this.$Message.success("文件还在上传中请等待一会~");
        return;
      }
      this.btnLoading = true;
      let params = {};
      if (this.contentInfo.type == "1") {
        let images = [];
        this.contentInfo.imgfiles.forEach((item) => {
          images.push(item.file);
        });
        params = {
          c_home_page_banner_type: this.contentInfo.type,
          c_home_page_title: this.contentInfo.title,
          c_home_page_banner_content: this.contentInfo.content,
          c_home_page_banner_image: images,
        };
      } else if (this.contentInfo.type == "2") {
        params = {
          c_home_page_banner_type: this.contentInfo.type,
          c_home_page_title: this.contentInfo.title,
          c_home_page_banner_content: this.contentInfo.content,
          c_home_page_banner_video: this.contentInfo.videofiles.file,
        };
      }
      homeEdit(params)
        .then((res) => {
          this.$Message.success("保存成功");
          this.btnLoading = false;
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addForm();
        } else {
          this.addModal = true;
          return;
        }
      });
    },
    onPause() {
      const video = this.$refs.video;
      video.pause();
    },
  },
};
</script>

<style lang="less">
.demo-upload-list {
  display: inline-block;
  width: 200px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.imgList {
  width: 100%;
  white-space: nowrap;
  overflow: auto;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
